from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from .agent_tools import synonym_expand_tool, es_search_tool, mysql_search_tool
import os

# 获取DASHSCOPE API密钥（从系统环境变量）
DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY")

# 初始化DASHSCOPE模型
llm = ChatOpenAI(
    model="qwen-plus",
    api_key=DASHSCOPE_API_KEY,
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    temperature=0.2,
    max_tokens=2048
)

agent = initialize_agent(
    [synonym_expand_tool, es_search_tool, mysql_search_tool],
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

def agent_search(query, category=None, sort='relevance', filters=None, limit=20, page=1):
    prompt = (
        f"请帮我搜索：{query}，"
        f"类别：{category or '全部'}，"
        f"排序：{sort}，"
        f"筛选条件：{filters or '无'}，"
        f"每页{limit}条，第{page}页。"
        "请自动纠错、扩展同义词，但**只扩展与搜索词直接相关的词，不要泛化到其它类别或同类大类**，"
        "优先用ES，无法用ES时用MySQL，"
        "结果按类别分组，突出显示标题、摘要、来源，返回分页数据。"
    )
    return agent.run(prompt) 